<template>
  <view class="purchase-container">
    <!-- 头部信息 -->
    <view class="header-info">
<!--      <view class="form-group">-->
<!--        <text class="label">采购单号</text>-->
<!--        <text class="value">{{ purchaseOrderNo }}</text>-->
<!--      </view>-->
      <view class="form-group">
        <text class="label">采购日期</text>
        <uni-datetime-picker
            v-model="purchaseDate"
            type="date"
            :default-date="purchaseDate"
            @change="onPurchaseDateChange"
        ></uni-datetime-picker>
      </view>
    </view>

    <!-- 已选商品列表 -->
    <view class="selected-products">
      <view class="section-title">已选商品</view>

      <view class="empty-list" v-if="selectedProducts.length === 0">
        <text>暂无选择的商品</text>
      </view>

      <!-- 优化后的商品列表（调整按钮间距） -->
      <view class="product-item" v-for="(item, index) in selectedProducts" :key="item.productId">
        <view class="product-name-col">
          <text>{{ item.productName || '未命名商品' }}</text>
        </view>
        <view class="product-action-col">
          <view class="quantity-control">
            <uni-number-box
                v-model="item.quantity"
                :min="1"
                :max="999"
                @change="onQuantityChange(item)"
                class="number-box"
            ></uni-number-box>
          </view>
          <view class="delete-btn" @click="removeProduct(index)">
            <uni-icons type="trash" size="24"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加商品按钮 -->
    <view class="add-product-btn" @click="openProductSelector">
      <uni-icons type="plusempty" size="30"></uni-icons>
      <text>添加商品</text>
    </view>

    <!-- 底部统计信息（数字加粗突出） -->
    <view class="summary">
      <view class="item">
        <text>商品总数</text>
        <text class="total-quantity">{{ totalQuantity }}</text>
      </view>
      <view class="item">
        <text>预计总金额</text>
        <text class="total-amount">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitPurchase">
      <text>提交采购单</text>
    </view>

    <!-- 商品选择器模态框 -->
    <view class="modal" v-if="showProductSelector">
      <view class="modal-mask" @click="closeProductSelector"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="title">选择商品</text>
          <view class="close-btn" @click="closeProductSelector">
            <uni-icons type="closeempty" size="30"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <ProductSelector
              :selectedIds="selectedProductIds"
              @select="onProductSelect"
          ></ProductSelector>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import ProductSelector from '@/components/product/ProductSelector.vue';

export default {
  components: {
    ProductSelector
  },
  data() {
    return {
      // purchaseOrderNo: 'PO' + new Date().getTime(),
      quantity: 1,
      purchaseDate: this.$dateUtils.getLocalDate(),
      selectedProducts: [],
      showProductSelector: false,
      purchaseFrom:{}
    }
  },
  onReady: function () {
    this.purchaseDate = this.$dateUtils.getLocalDate();
  },
  computed: {
    selectedProductIds() {
      return this.selectedProducts.map(item => item.productId);
    },
    totalQuantity() {
      return this.selectedProducts.reduce((sum, item) => sum + (item.quantity || 0), 0);
    },
    totalAmount() {
      return this.selectedProducts.reduce((sum, item) => sum + (item.quantity || 0) * item.defaultPurchasePrice, 0);
    }
  },
  methods: {
    openProductSelector() {
      this.showProductSelector = true;
    },
    closeProductSelector() {
      this.showProductSelector = false;
    },
    onProductSelect(product) {
      var productFag =this.selectedProducts.some(selectedProduct => selectedProduct.productId === product.productId);
      if(productFag){
        uni.showToast({title: '此商品已添加', icon: 'success', duration: 1500});
        return;
      }
      this.selectedProducts.push({...product, quantity: 1});
      this.showProductSelector = false;
      uni.showToast({title: '已添加商品', icon: 'success', duration: 1500});
    },
    removeProduct(index) {
      this.selectedProducts.splice(index, 1);
      console.log('removeProduct:',this.selectedProducts)
    },
    onQuantityChange(selProduct) {
      console.log('selProduct:',selProduct)
      // 根据 productId 查找对应的商品项
      // const product = this.selectedProducts.find(item => item.productId === selProduct.productId);
      // if (product) {
      //   // 仅修改对应商品的数量
      //   product.quantity = this.quantity;
      // } else {
      //   console.error(`未找到商品ID=${productId} 的商品项`);
      // }
      console.log('onQuantityChange:',this.selectedProducts)

    },
    onPurchaseDateChange(e) {
      this.purchaseDate = e;
    },
    submitPurchase() {
      if (!this.selectedProducts.length) {
        uni.showToast({title: '请选择商品', icon: 'none'});
        return;
      }
      uni.showLoading({title: '提交中...'});
      this.purchaseFrom = {
        orderDate:this.purchaseDate,
        orderItems:this.selectedProducts,
        userId:this.$store.state.user.id
      }
      console.log('this.purchaseFrom:',this.purchaseFrom)
      this.req({
        url: '/purchase/createOrder',
        method: 'POST',
        data: this.purchaseFrom
      }).then(res => {
        uni.hideLoading();
        uni.showToast({title: '提交成功', icon: 'success', duration: 2000});
      })


    }
  }
}
</script>

<style>
.purchase-container {
  height: 100vh;
  background-color: #f8f8f8;
}

.header-info {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.form-group {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;
}

.label {
  width: 200rpx;
  font-size: 28rpx;
  color: #333;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #666;
}

.selected-products {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.section-title {
  padding: 20rpx;
  font-size: 32rpx;
  font-weight: bold;
  border-bottom: 1rpx solid #eee;
}

.empty-list {
  text-align: center;
  padding: 50rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 商品列表布局优化 */
.product-item {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  align-items: center;
}

.product-name-col {
  flex: 1;
}

.product-name-col text {
  font-size: 30rpx;
}

.product-action-col {
  flex: 3;
  display: flex;
  //align-items: center;
  //justify-content: space-between;
  justify-content: flex-end;
}

.quantity-control {
  //margin-right: 25rpx;
  width: 220rpx;
}

/* 增加间距至25rpx */
.number-box {
  width: 120rpx;
}

.delete-btn {
  //padding: 10rpx;
  color: #999;
}

.add-product-btn {
  background-color: #fff;
  padding: 25rpx 0;
  text-align: center;
  font-size: 32rpx;
  color: #007aff;
  margin-bottom: 20rpx;
}

/* 统计信息数字加粗 */
.summary {
  display: flex;
  background-color: #fff;
  padding: 25rpx 0;
  margin-bottom: 20rpx;
  justify-content: space-around;
}

.summary .item {
  text-align: center;
  font-size: 32rpx;
}

.summary .total-quantity {
  font-weight: bold;
  color: #007aff;
}

/* 加粗并设为蓝色 */
.summary .total-amount {
  font-weight: bold;
  color: #e54d42;
}

/* 加粗并设为红色 */

.submit-btn {
  background-color: #007aff;
  color: #fff;
  text-align: center;
  padding: 30rpx 0;
  font-size: 36rpx;
  border-radius: 10rpx;
  margin: 0 20rpx;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  height: 80%;
  border-radius: 20rpx 20rpx 0 0;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx;
  border-bottom: 1rpx solid #eee;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.close-btn {
  padding: 10rpx;
}

.modal-body {
  flex: 1;
  overflow-y: auto;
}
</style>